<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Create New Item</title>

    <style>
        html {
            margin: 0;
            padding: 0;
            height: 100%;
            background: url('img/background.png') no-repeat center center;
            background-size: 95%;
            background-color: #000;
            background-attachment: fixed;
            image-rendering: pixelated;
        }

        body {
            margin: 0;
            padding: 0;
            min-height: 100%;
        }

        #top {
            height: 50px;
            width: 100%;
            background-color: #000;
            display: flex;
            align-items: center; /* 垂直居中 */
            justify-content: space-between; /* 左右两端对齐 */
            padding: 0 10px;
            box-sizing: border-box;
        }

        #loge {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        #loge img {
            height: 40px;
            width: 40px;
            image-rendering: pixelated;
        }

        #loge p {
            color: #d1d1d1;
            font-size: 20px;
            margin: 0;
        }

        #login {
            height: 50px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        #login p {
            color: #d1d1d1;
            font-size: 16px;
            margin: 0;
            user-select: none;
        }

        .operaButton {
            height: 30px;
            padding: 0 12px;
            background-color: #3a3a3a;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 10px;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.2s ease;
            box-sizing: border-box;
        }

        .operaButton:hover {
            background-color: #505050;
        }

        #title {
            width: 100%;
        }

        h1 {
            font-size: 36px;
            text-align: center;
            margin: 0 0 20px 0;
            color: #d1d1d1;
        }

        #content {
            margin: 0 auto;
            width: 75%;
            min-height: calc(100vh - 50px);
            background-color: #2c2925;
        }

        /* 表单整体样式 */
        #itemForm {
            max-width: 700px;
            margin: 0 auto;
        }

        /* 表单区域标题 */
        #itemForm h2 {
            text-align: center;
            margin: 20px 0 10px;
            color: #f0f0f0;
        }

        /* 表单内每行排版 */
        #itemForm div {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }

        /* 标签样式 */
        #itemForm label {
            margin: 5px 8px;
            min-width: 100px;
            text-align: right;
        }

        /* 输入框、选择框统一风格 */
        #itemForm input[type="text"],
        #itemForm input[type="number"],
        #itemForm select,
        #itemForm textarea {
            background-color: #3a3a3a;
            color: #d1d1d1;
            border: 1px solid #555;
            border-radius: 4px;
            padding: 6px 10px;
            margin: 5px;
            outline: none;
        }

        #itemForm input[type="file"] {
            color: #d1d1d1;
        }

        /* 多选框道具池样式 */
        #itemPools {
            background-color: #3a3a3a;
            color: #d1d1d1;
            border: 1px solid #555;
            border-radius: 4px;
            padding: 5px;
            width: 100%;
            box-sizing: border-box;
        }

        /* 按钮样式 */
        #itemForm button {
            background-color: #505050;
            color: #d1d1d1;
            border: none;
            padding: 8px 14px;
            border-radius: 6px;
            cursor: pointer;
            margin: 5px;
        }

        #itemForm button:hover {
            background-color: #707070;
        }

        /* 协同列表样式 */
        #synergyList div {
            background-color: #3a3a3a;
            padding: 6px 10px;
            border-radius: 4px;
            margin: 5px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        /* hr 分隔线美化 */
        #itemForm hr {
            border: 0;
            height: 1px;
            background: #444;
            margin: 20px 0;
        }

        /* 提交按钮单独样式 */
        #submitBtn {
            width: 200px;
            font-size: 18px;
            background-color: #707070;
            color: #f0f0f0;
            border: none;
            padding: 12px 0;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        #submitBtn:hover {
            background-color: #909090;
        }
    </style>
</head>
<body>
    <div id="top">
        <div id="loge">
            <img src="img/site_avatar_isaac_l.webp" alt="Isaac Wiki">
            <p>以撒的结合Wiki</p>
        </div>
        <div id="login">
            <!-- 预留登录/注册区域 -->
        </div>
    </div>
    <div id="content">
        <div id="title">
            <h1>创建道具</h1>
        </div>
        <form id="itemForm" style="padding:20px; color:#d1d1d1;">

            <!-- 第一区域：道具基本信息 -->
            <h2>道具基本信息</h2>

            <div>
                <label>ID：</label>
                <input type="number" id="itemId" name="itemId" required>
                <label>名称：</label>
                <input type="text" id="itemName" name="itemName" required>
            </div>
            <br>
            <div>
                <label>品质(0-4)：</label>
                <input type="number" id="quality" name="quality" min="0" max="4" required>
                <label>类型：</label>
                <select id="itemType" name="itemType" required>
                    <option value="">请选择</option>
                    <option value="1">主动道具</option>
                    <option value="0">被动道具</option>
                </select>
            </div>
            <br>
            <div id="powerRow" style="display:none;">
                <label>充能：</label>
                <input type="number" id="power" name="power">
            </div>
            <br>
            <div>
                <label>效果：</label>
                <textarea id="effect" name="effect" rows="3" cols="50"></textarea>
            </div>

            <hr>

            <!-- 第二区域：道具属性 -->
            <h2>道具属性</h2>

            <div>
                <label>生命上限：</label>
                <input type="text" id="maxHp" name="maxHp">
                <label>生命恢复：</label>
                <input type="text" id="hp" name="hp">
            </div>
            <br>
            <div>
                <label>攻击力：</label>
                <input type="text" id="damage" name="damage">
                <label>射速：</label>
                <input type="text" id="tears" name="tears">
            </div>
            <br>
            <div>
                <label>攻击范围：</label>
                <input type="text" id="range" name="range">
                <label>弹速：</label>
                <input type="text" id="shotSpeed" name="shotSpeed">
            </div>
            <br>
            <div>
                <label>速度：</label>
                <input type="text" id="speed" name="speed">
                <label>幸运：</label>
                <input type="text" id="lucky" name="lucky">
            </div>
            <br>
            <div>
                <label>恶魔房开房率：</label>
                <input type="text" id="devilProbability" name="devilProbability">
                <label>天使房转化率：</label>
                <input type="text" id="angelProbability" name="angelProbability">
            </div>

            <hr>

            <!-- 第三区域：协同效应 -->
            <h2>协同效应</h2>
            <div>
                <label>协同道具ID：</label>
                <input type="number" id="synergyItemId">
                <label>协同效应：</label>
                <input type="text" id="synergyEffect">
                <button type="button" id="addSynergyBtn">添加</button>
            </div>
            <div id="synergyList" style="margin-top:10px;"></div>

            <hr>

            <!-- 道具池选择 -->
            <h2>道具池</h2>
            <select id="itemPools" multiple size="8">
                <option value="1">宝箱房</option>
                <option value="2">商店</option>
                <option value="3">头目房</option>
                <option value="4">恶魔房</option>
                <option value="5">天使房</option>
                <option value="6">隐藏房</option>
                <option value="7">图书馆</option>
                <option value="8">赌博乞丐</option>
                <option value="9">金箱子</option>
                <option value="10">红箱子</option>
                <option value="11">乞丐</option>
                <option value="12">恶魔乞丐</option>
                <option value="13">诅咒房</option>
                <option value="14">钥匙乞丐</option>
                <option value="15">电池乞丐</option>
                <option value="16">妈妈的箱子</option>
                <option value="17">夹娃娃机</option>
                <option value="18">究极隐藏房</option>
                <option value="19">星象房</option>
                <option value="20">旧箱子</option>
                <option value="21">宝宝商店</option>
                <option value="22">木箱子</option>
                <option value="23">腐烂乞丐</option>
            </select>

            <hr>

            <!-- 图片选择 -->
            <h2>图片</h2>
            <input type="file" id="itemImg" name="itemImg">

            <hr>

            <!-- 提交按钮 -->
            <div style="display: flex; justify-content: center;">
                <button type="button" id="submitBtn">提交</button>
            </div>

        </form>
    </div>
</body>

<script src="js/jQuery-3.7.1.min.js"></script>
<script>
    $(document).ready(function () {
        const jwt = localStorage.getItem("jwt");
        const loginDiv = $("#login");

        if (jwt) {
            // 有 jwt，显示头像、名称和登出按钮
            const name = localStorage.getItem("name") || "用户";
            const imgUrl = localStorage.getItem("imgUrl") || "img/default_avatar.png";

            const userHtml = `
    <img src="${imgUrl}" alt="头像" id="userAvatar" style="height:30px; width:30px; border-radius:50%; vertical-align:middle; margin-right:8px; object-fit:cover;">
    <p id="userName" style="color:#d1d1d1; font-size:16px; margin:0; line-height:30px; display:inline-block; vertical-align:middle;">${name}</p>
    <div id="logoutBtn" class="operaButton" style="margin-left:12px;">
        <p>登出</p>
    </div>
`;
            loginDiv.html(userHtml);

            // 登出按钮暂时不绑定事件，后续可以加
            $("#logoutBtn").click(() => {
                // 清除登录相关的 localStorage 信息
                localStorage.removeItem("jwt");
                localStorage.removeItem("name");
                localStorage.removeItem("imgUrl");
                // 你如果存了别的登录相关信息，也一起清理，比如 id、username 等等
                localStorage.removeItem("id");
                localStorage.removeItem("username");

                // 刷新页面
                location.reload();
            });

            // ✅ 绑定头像和用户名点击跳转 userInfo.html
            $("#userAvatar, #userName").click(() => {
                window.open("userInfo.html");
            });

        } else {
            // 未登录，提示并跳转
            alert("未登录，请先登录！");
            window.location.href = "ItemList.html";
        }

        // 主动道具显示充能框
        $("#itemType").change(function() {
            if ($(this).val() == "1") {
                $("#powerRow").show();
            } else {
                $("#powerRow").hide();
                $("#power").val("");
            }
        });

// 添加协同效应
        $("#addSynergyBtn").click(function() {
            const itemId = $("#synergyItemId").val();
            const effect = $("#synergyEffect").val();

            if (itemId === "" || effect === "") {
                alert("协同道具ID和效应不能为空！");
                return;
            }

            const synergyHtml = `
        <div style="margin:5px 0;">
            ID: ${itemId}, 效应: ${effect}
            <button type="button" class="removeSynergyBtn">删除</button>
        </div>
    `;
            $("#synergyList").append(synergyHtml);

            // 清空输入框
            $("#synergyItemId").val("");
            $("#synergyEffect").val("");
        });

// 删除协同效应
        $("#synergyList").on("click", ".removeSynergyBtn", function() {
            $(this).parent().remove();
        });


        // 提交按钮事件
        $("#submitBtn").click(function() {
            const jwt = localStorage.getItem("jwt");
            const userId = localStorage.getItem("id");

            // 检查必填项
            if ($("#itemId").val() === "" || $("#itemName").val() === "" || $("#quality").val() === "" || $("#itemType").val() === "") {
                alert("请填写完整道具ID、名称、品质和类型！");
                return;
            }

            // 如果是主动道具，则充能不能为空
            if ($("#itemType").val() === "1" && $("#power").val().trim() === "") {
                alert("主动道具的充能不能为空！");
                return;
            }

            // 检查图片是否上传
            const fileInput = $("#itemImg")[0];
            if (fileInput.files.length === 0) {
                alert("请上传道具图片！");
                return;
            }

            // 上传图片
            const formData = new FormData();
            formData.append("file", fileInput.files[0]);

            $.ajax({
                url: "http://localhost:8080/user/uploadItemImage",  // 换成你实际后端地址
                type: "POST",
                headers: {
                    "token": jwt
                },
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function(res) {
                    if (res.code !== 1) {
                        alert("图片上传失败: " + res.msg);
                        return;
                    }

                    const imageUrl = res.data;

                    // 组织 createItem 数据
                    const itemId = Number($("#itemId").val());
                    const itemPools = [];
                    $("#itemPools option:selected").each(function() {
                        itemPools.push({
                            id: Number($(this).val()),
                            name: $(this).text()
                        });
                    });

                    const synergies = [];
                    $("#synergyList div").each(function() {
                        const text = $(this).text();
                        const idMatch = text.match(/ID: (\d+)/);
                        const effectMatch = text.match(/效应: (.+)/);
                        if (idMatch && effectMatch) {
                            synergies.push({
                                itemAId: itemId,
                                itemBId: Number(idMatch[1]),
                                effect: effectMatch[1].trim()
                            });
                        }
                    });

                    const data = {
                        item: {
                            id: itemId,
                            name: $("#itemName").val(),
                            quality: Number($("#quality").val()),
                            type: Number($("#itemType").val()),
                            power: $("#power").val() === "" ? null : Number($("#power").val()),
                            effect: $("#effect").val() === "" ? null : $("#effect").val(),
                            createId: Number(userId),
                            changeId: Number(userId)
                        },
                        itemsAttributes: {
                            id: itemId,
                            maxHp: nullableVal($("#maxHp").val()),
                            hp: nullableVal($("#hp").val()),
                            damage: nullableVal($("#damage").val()),
                            tears: nullableVal($("#tears").val()),
                            range: nullableVal($("#range").val()),
                            shotSpeed: nullableVal($("#shotSpeed").val()),
                            speed: nullableVal($("#speed").val()),
                            lucky: nullableVal($("#lucky").val()),
                            devilProbability: nullableVal($("#devilProbability").val()),
                            angelProbability: nullableVal($("#angelProbability").val())
                        },
                        synergies: synergies,
                        itemPoolTypes: itemPools,
                        itemImgPath: {
                            itemId: itemId,
                            path: imageUrl
                        }
                    };

                    // 创建道具
                    $.ajax({
                        url: "http://localhost:8080/user/createItem",  // 换成你实际后端地址
                        type: "POST",
                        headers: {
                            "token": jwt
                        },
                        contentType: "application/json",
                        data: JSON.stringify(data),
                        success: function(res) {
                            if (res.code === 1) {
                                alert("道具创建成功！");
                                window.location.href = "ItemList.html";
                            } else {
                                alert("道具创建失败: " + res.msg);
                            }
                        },
                        error: function() {
                            alert("提交道具时发生错误！");
                        }
                    });

                },
                error: function() {
                    alert("上传图片失败！");
                }
            });
        });

// 小函数：空字符串转 null，其他照传
        function nullableVal(val) {
            return val === "" ? null : val;
        }

    })
</script>
</html>